import re
import urllib.request, urllib.error
import csv
import sys
import io
import time
import random
import requests
from bs4 import BeautifulSoup  # 网页解析
import re  # 正则表达式文字匹配
import os
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 正则表达式
findlink = re.compile(r'a href="(.*?)">')   # 电影链接
findImageSrc = re.compile(r'<img.*src="(.*?)"', re.S)   # 图片链接
findTitle = re.compile(r'<span class="title">(.*)</span>')      # 标题
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')   # 评分
findJudge = re.compile(r'<span>(\d*)人评价</span>')    # 人数
findInq = re.compile(r'<span class="inq">(.*)</span>')  # 概况
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)  # 相关信息
findYear = re.compile(r'(\d{4})')  # 年份
findCountry = re.compile(r'\d{4}\s+([^\d\s]+)')  # 国家
findDirector = re.compile(r'导演: (.*?)\s')  # 导演
findCategory = re.compile(r'(\S+ \S+)$')  # 类别

def main():
    baseurl = "https://movie.douban.com/top250?start=0"
    savepath = "豆瓣电影Top250.csv"

    # 检查文件是否存在
    if os.path.exists(savepath):
        print(f"{savepath} 已经存在，不再爬取数据。")
    else:
        datalist = getdata(baseurl)
        # print(datalist)
        saveData(datalist, savepath)

def askURL(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36 HBPC/12.1.3.310"
    }

    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html

# 爬取网页
def getdata(baseurl):
    datalist = []  # 解析数据
    for i in range(0, 10):
        url = baseurl + str(i * 25)
        html = askURL(url)
        if not html:
            continue
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all('div', class_="item"):
            data = []
            item = str(item)
            link = re.findall(findlink, item)[0]
            data.append(link)
            image = re.findall(findImageSrc, item)[0]
            data.append(image)

            title = re.findall(findTitle, item)
            if len(title) == 2:
                ctitle = title[0]
                data.append(ctitle)
                otitle = title[1].replace("/", "")
                data.append(otitle.strip())
            else:
                data.append(title[0])
                data.append("")

            rating = re.findall(findRating, item)[0]  # 添加评分
            data.append(rating)

            judgeNum = re.findall(findJudge, item)[0]  # 添加评价人数
            data.append(judgeNum)

            inq = re.findall(findInq, item)
            if len(inq) != 0:
                inq = inq[0].replace("。", "")
                data.append(inq)
            else:
                data.append("")

            bd = re.findall(findBd, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?', " ", bd)
            bd = re.sub('/', " ", bd)
            bd = re.sub('\xa0', " ", bd)
            bd = re.sub('\n', " ", bd)
            data.append(bd.strip())

            # 提取年份
            year = re.findall(findYear, bd)
            if year:
                data.append(year[0])
            else:
                data.append("")

            # 提取国家
            country = re.findall(findCountry, bd)
            if country:
                country = country[0].strip()
                if country in ["中国大陆", "中国香港"]:
                    country = "中国"
                data.append(country)
            else:
                data.append("")

            # 提取导演
            director = re.findall(findDirector, bd)
            if director:
                director = director[0].strip()
                data.append(director)
            else:
                data.append("")

            # 提取类别
            category = re.findall(findCategory, bd)
            if category:
                category = category[0].strip()
                data.append(category)
            else:
                data.append("")

            datalist.append(data)
        time.sleep(random.uniform(2, 3))  # 每次请求后暂停随机时间
    # print(datalist)
    return datalist
def saveData(datalist, savepath):
    col = ["movie_detail_link", "image_link", "title", "rating", "number_of_reviews", "overview", "relevant_information", "year", "country", "director", "category"]
    with open(savepath, 'w', newline='', encoding='utf-8-sig') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(col)
        
        for i in range(len(datalist)):
            print(f"第{i+1}条")
            data = datalist[i]
            # 合并 chinese_title 和 foreign_title
            title = data[2] if data[2] else data[3]
            data[11] = data[7][-2:]
            # 构建新的数据行
            new_data = [data[0], data[1], title, data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11]]
            
            # 写入文件
            writer.writerow(new_data)
    print("保存完毕！")
# def saveData(datalist, savepath):
#     # print("保存中...")
#     # with open(savepath, 'w', newline='', encoding='utf-8-sig') as csvfile:
#     #     writer = csv.writer(csvfile)
#     #     col = ["movie_detail_link", "image_link", "title", "rating", "number_of_reviews", "overview", "relevant_information", "year", "country", "director"]
#     #     writer.writerow(col)
#     #     for i in range(len(datalist)):
#     #         print(f"第{i+1}条")
#     #         data = datalist[i]
#     #         # 合并 chinese_title 和 foreign_title
#     #         title = data[2] if data[2] else data[3]
#     #         # 构建新的数据行
#     #         new_data = [data[0], data[1], title, data[4], data[5], data[6], data[7], data[8], data[9], data[10]]
#     #         writer.writerow(new_data)
#     # print("保存完毕！")
#     print("打印CSV数据...")
#     col = ["movie_detail_link", "image_link", "title", "rating", "number_of_reviews", "overview", "relevant_information", "year", "country", "director", "category"]
#     print(','.join(col))
#     for i in range(len(datalist)):
#         data = datalist[i]
#         # 合并 chinese_title 和 foreign_title
#         title = data[2] if data[2] else data[3]
#         data[11] = data[7][-2:]
#         # 构建新的数据行
#         new_data = [data[0], data[1], title, data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11]]
#         print(','.join(['"' + str(item).replace('"', '""') + '"' for item in new_data]))
#     print("打印完毕！")

if __name__ == "__main__":
    main()
    print("爬取完毕！")